import React, { memo, useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import { IndicatorWrapper } from './style';

const Indicator = memo((props) => {
  const { selectIndex= 0 } = props;

  const contentRef = useRef();
  useEffect(() => {
    // console.log(selectIndex, 'useEffect');
    //  selectIndex 对应的item
    const selectIndexItem = contentRef.current.children[selectIndex];
    const itemOffsetLeft = selectIndexItem.offsetLeft;
    const itemWidth = selectIndexItem.clientWidth;
    // content 的宽度
    const contentWidth = contentRef.current.clientWidth;
    const contentSrcoll = contentRef.current.scrollWidth;
    //   获取selectIndex 要滚动的距离
    let distance = itemOffsetLeft + itemWidth * 0.5 - contentWidth * 0.5;
    //   console.log(distance);
    // 特殊情况处理
    if (distance < 0) distance = 0; // 左边特殊情况处理
    const totalDistance = contentSrcoll - contentWidth;
    if (distance > totalDistance) distance = totalDistance; // 右边特殊情况处理

    contentRef.current.style.transform = `translate(${-distance}px)`;
  }, [selectIndex]);
  return (
    <IndicatorWrapper>
      <div className="indicator-content" ref={contentRef}>
        {props.children}
      </div>
    </IndicatorWrapper>
  );
});

Indicator.propTypes = {
  selectIndex: PropTypes.number,
};
export default Indicator;
